package api;

import com.alibaba.fastjson.JSON;
import domain.User;

import exception.LoginException;
import service.UserService;
import utils.GetRequestJsonUtils;
import com.alibaba.fastjson.JSONObject;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;


public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //第一步：提取请求中的账号密码
        JSONObject object=null;
        try {
            object = GetRequestJsonUtils.getRequestJsonObject(req);
        }catch (Exception e){
        // e.printStackTrace();
            Response build=Response.build(ResponseCode.ERROR,e.getMessage());
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(JSON.toJSON(build).toString());
        }
        String userString=object.getString("user");
        System.out.println(userString);
         //第二步：把账号密码转换成java对象
        User user=JSON.parseObject(userString,User.class);
          //第三步：把该对象对应数据库表中记录查询出来
        UserService userService=new UserService();
        User userDB=null;
        Response build=null;
        try {
            userDB = userService.login(user);
            //经过service返回的一定是成功登录          第四步：判断，如果不存在记录，则没有该用户，存在该用户，则对照密码，
            //第五步：如果账号密码都相同，创建session，往session中添加属性user
            //第六步：把sessio的id添加到cookie中，再把cookie添加到消息中
            HttpSession session=req.getSession();
            session.setAttribute("user",userDB);//相当于为该浏览器发放了一个凭证
            Cookie cookie=new Cookie("JSESSIONID",session.getId());
            resp.addCookie(cookie);
            String url=null;
            if(userDB.getRole().equals("超级用户")){
                url="/admin/login/home.jsp";
            }else {
                url= "/client/myAccount.jsp";
            }
            build=Response.build(ResponseCode.SUCCESS_LOGIN,url);
        }catch (LoginException e){
            //把异常消息内容和消息代码添加到ResponseCode中去，然后封装成消息
            e.printStackTrace();
            build=Response.build(e.getResponseCode());
        }
            //第七步：封装消息对象
            //第八步：转换消息对象为字符串，返回给浏览器
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSON(build).toString());
    }

}
